import { asyncRouterMap, constantRouterMap } from '@/config/router.config'

/**
 * 过滤账户是否拥有某一个权限，并将菜单从加载列表移除
 *
 * @param permissionKeys
 * @param route
 * @returns {boolean}
 */
function hasPermission (permissionKeys, route) {
  if (route.meta && route.meta.permission) {
    let flag = false
    for (let i = 0, len = permissionKeys.length; i < len; i++) {
      flag = route.meta.permission.includes(permissionKeys[i])
      if (flag) {
        break
      }
    }
    return flag
  }
  return true
}

/**
 *
 * @param {*异步路由} routerMap
 * @param {*权限组} permissionKeys
 */
function filterAsyncRouter (routerMap, permissionKeys) {
  const accessedRouters = routerMap.filter(route => {
      if (route.children && route.children.length) {
          route.children = filterAsyncRouter(route.children, permissionKeys)
          return route.children.length > 0
      } else {
          return hasPermission(permissionKeys, route)
      }
  })
  return accessedRouters
}

// 迭代获取permission key
function filterPermissionKeys (tree, arr) {
  arr.push(tree.key)
  if (tree.children && tree.children.length > 0) {
    tree.children.forEach(element => {
      filterPermissionKeys(element, arr)
    })
  }
}

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: [],
    permissionKeys: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    },
    SET_PERMISSIONKEYS (state, permissionKeys) {
      state.permissionKeys = permissionKeys
    }
  },
  actions: {
    GenerateRoutes ({ commit }, data) {
      return new Promise(resolve => {
        const { menuTreeNode } = data
        const permissionKeys = []
        filterPermissionKeys(menuTreeNode, permissionKeys)
        const accessedRouters = filterAsyncRouter(asyncRouterMap, permissionKeys)
        commit('SET_PERMISSIONKEYS', data.permissionSet)
        commit('SET_ROUTERS', accessedRouters)
        resolve()
      })
    }
  }
}

export default permission
